package com.ruoyi.srmcontract.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.log.annotation.OperLog;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.annotation.JsonView;
import com.ruoyi.srmcontract.domain.JacContract;
import com.ruoyi.srmcontract.service.IJacContractService;
import com.ruoyi.srmcontract.utils.MyUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 合同维护 提供者
 * 
 * @author ygx
 * @date 2020-08-04
 */
@Slf4j
@RestController
@RequestMapping("contract")
public class JacContractController extends MyUtils
{
	
	@Autowired
	private IJacContractService jacContractService;

	
	/**
	 * 查询${tableComment}
	 */
	@GetMapping("get/{contractId}")
	@JsonView(value = JacContract.contractListView.class)
	public R get(@PathVariable("contractId") Long contractId)
	{   
		startPage();
		return jacResult(jacContractService.selectJacContractById(contractId));
		
	}
	
	/**
	 * 根据生成的jflow的uuid查询合同列表
	 * @param uuid
	 * @return
	 */
	@GetMapping("getContractByUuid")
	@JsonView(value = JacContract.contractListView.class)
	public R get(@RequestParam("uuid") String uuid)
	{   
		startPage();
		return result(jacContractService.selectCodeByUuid(uuid));
		
	}
	
	/**
	 * 查询合同维护列表
	 */
	@GetMapping("list")
	@JsonView(value = JacContract.contractListView.class)
	public R list(JacContract jacContract)
	{   
		startPage();
        return result(jacContractService.selectJacContractList(jacContract));
	}
	
	/**
	 * 查询合同日志
	 */
	@GetMapping("getLog")
	@JsonView(value = JacContract.contractLogView.class)
	public R getLog(JacContract jacContract)
	{
		startPage();
        return result(jacContractService.selectLog(jacContract));
	}
	
	
	/**
	 * 查询合同维护列表
	 */
	@PostMapping("postlist")
	@JsonView(value = JacContract.contractListView.class)
	public R postlist(@RequestBody JacContract jacContract)
	{
		startPage();
        return result(jacContractService.selectJacContractList(jacContract));
	}
	
	
	/**
	 * 导出到excel
	 * @param jacContractItem
	 * @param response
	 * @throws IOException
	 */
    @GetMapping("/exp")
    @ResponseBody
    public void exp(JacContract jacContract, HttpServletResponse response) throws IOException {
    	response.setHeader("code","0");
    	try {
			String datetime = new SimpleDateFormat("yyyymmddHHmmss").format(new Date());
			String filename = "合同生效确认" + datetime + ".xlsx";
			startPage();
			List<JacContract> list = jacContractService.selectExcelList(jacContract); //被导出数据本身，这里的list只是测试，具体业务可能要进行筛选
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
			EasyExcel.write(response.getOutputStream(), JacContract.class).sheet("模板1").doWrite(list);//‘模板1’可根据业务内容自行变更
		} catch (Exception e) {
			response.setHeader("code","500");
			log.error("下载失败",e);
		}
    }
	
	
	/**
	 * 生成合同号（如：HTBJ202008030001）
	 */
	@GetMapping("getContractCode/{companycode}")
	public R getContractCode(@PathVariable("companycode") String companycode)
	{
		
		return jacResultString("constractCode",jacContractService.createContractCode(companycode,"HT"));
	}
	
	
	/**
	 * 新增保存合同维护
	 */
	@PostMapping("save")
	@OperLog(title = "合同管理", businessType = BusinessType.INSERT)
	public Map<String, String> addSave(@RequestBody JacContract jacContract)
	{		
		return jacResultMsg(jacContractService.insertJacContract(jacContract));
	}

	/**
	 * 修改保存合同维护
	 */
	@PostMapping("update")
	public R editSave(@RequestBody JacContract jacContract)
	{		
		return toAjax(jacContractService.updateJacContract(jacContract));
	}
	
	/**
	 * 修改合同状态并写入日志
	 */
	@PostMapping("updateStatus")
	public Map<String,Object> updateStatus(@RequestBody Map<String,List<JacContract>> datas)
	{	
		Map<String,Object> r = new HashMap<String,Object>();
		String result = jacContractService.updateContractStatus(datas);
		if (result == "1")
		{
		r.put("msg", "success");
		r.put("code", "0");
		return r;
		}
		if (StringUtils.contains(result, "管理员"))
		{
				r.put("msg", result);
				r.put("code", "500");
				return r;
		}
		if (StringUtils.contains(result, "uuid"))
		{   
			Map<String,String> uuid = new HashMap<String,String>();
			uuid.put("uuid", result.replace("uuid", ""));
			r.put("msg", "success");
			r.put("code", "0");
			r.put("rows",uuid);
			return r;
			
		}
			else
		{
			r.put("msg", result);
			r.put("code", "505");
			return r;
		}
	}
	
	/**
	 * 批量修改保存合同维护
	 */
	@PostMapping("updates")
	public R editSaves(@RequestBody Map<String,List<JacContract>> datas)
	{		
		return toAjax(jacContractService.updateJacContracts(datas));
	}
	
	/**
	 * 删除${tableComment}
	 */
	@PostMapping("remove")
	public  Map<String,String> remove(String ids)
	{	
		Map<String,String> r = new HashMap<String,String>();
		String result = jacContractService.deleteJacContractByIds(ids);
		if (result == "1")
		{
		r.put("msg", "success");
		r.put("code", "0");
		}
		else 
		{
			r.put("msg", result);
			r.put("code", "500");
		}
		return r;
	}
	
    /**
     * 根据参数类型获取参数值（比如传入参数类型ContractYear 获取定义的合同年份）
     * @param paramtype
     * @return
     */
	@GetMapping("getContractyear/{paramtype}")
    public Map<String,Object> getContractyear(@PathVariable("paramtype") String paramtype)
    {   
    	Map<String, Object> m = new HashMap<>();
    	m.put("code","0");
    	m.put("msg","success");
    	m.put("rows",jacContractService.getContractyear(paramtype));
    	return m;
    }
	
}
